import GridCellEditWrapper from '@/components/form/gridcelleditwrapper';
import { BaseSelect } from '@/components/form/loupeselect';
import { symbolPattern } from '@/utils/regexp';
import { getAvatar } from '@/utils/user';
import { getGantPopupContainer } from '@/utils/utils';
import { Avatar } from 'antd';
import type { ReactElement } from 'react';
import React, { useCallback, useMemo, useState, useEffect } from 'react';
import { getUserLabels } from '../utils';
import SelectorModal from './SelectorModal';
import { getDataApi } from './utils';
import { getUserInfo } from '@/utils/user';
import { getOrganizationInfo } from '@/utils/organization';
import { isEmpty } from 'lodash';

//默认查询关键字，为了带出来默认用户列表
// const defaultKeywords = "a";

const sizeCount = (size: string) => {
  let num_size = 28;
  if (size) {
    size == 'small' ? (num_size = 20) : null;
    size == 'large' ? (num_size = 36) : null;
  }
  return num_size;
};

interface userProps {
  userName: string;
  [key: string]: any;
}

interface SelectorFormItemProps {
  value: string; // 值
  users: userProps[]; // 锁定的用户可选列表, 约束可选用户
  roleCodes: string[]; // 指定的角色过滤参数
  excludeIds: string[]; //要排除的用户id

  isActive: boolean; // 是否过滤激活状态的用户
  valueProp: string; //值的key
  labelProp: string; // 显示字段的key
  size: string; // 尺寸
  multiple: boolean; //是否多选
  addonAfter: ReactElement; // 选择器后追加显示
  autoFocus: boolean; //是否自动聚焦
  showLoupe: boolean; //是否显示放大镜选择按钮
  isKeywords: boolean; //是否通过默认关键字带出默认用户列表
  edit?: string;

  onChange: (submitData: any, selectedRows: any) => void; //值改变的回调
  onBlur: () => void; //失去焦点的回调
  setCustomLabel: (user: userProps) => ReactElement; // 自定义label
  openMode: 'normal' | 'selectHide'; // 下拉打开的模式，默认为正常模式，selectHide为选择后隐藏下拉框但是又不失焦
  showDefaultData: boolean; // 是否默认显示数据
  isShowSkipButton?: boolean; //是否显示跳过按钮节点 默认为false
}

// 用于标识请求的时间戳，多次请求时，最后一次请求数据有效
let requestTimeStamp = Date.now();

const SelectorFormItem = (props: SelectorFormItemProps) => {
  const {
    users,
    value,
    valueProp,
    labelProp,
    size,
    multiple,
    autoFocus,
    excludeIds,
    onChange,
    onBlur,
    setCustomLabel = (user) => {
      const organizationInfo: any = getOrganizationInfo(user.organizationId);
      let suffix = '';
      if (organizationInfo?.orgName) {
        suffix = '-' + organizationInfo.orgName;
      }
      return user.userName + '-' + user.userLoginName + suffix;
    },
    showLoupe = true,
    roleCodes = [],
    openMode = 'normal',
    showDefaultData = true,
    isShowSkipButton = false,
    ...restProps
  } = props;

  // 进阶检索用户 弹框的展示状态
  const [visible, setVisible] = useState(false);
  const [dropdownVisible, setDropdownVisible] = useState(false);
  // grid 列表中使用，管理编辑和展示状态
  const [selectFocus, setSelectFocus] = useState(false);
  //数据
  const [data, setData] = useState<any>([]);

  //判断是否是虚拟用户
  const [virtalData, setVirtalData] = useState(!showDefaultData);
  //没有指定用户，也没有虚拟用户
  const [noData, setNoData] = useState(false);

  const extraProps = useMemo(() => {
    let extra = {};
    if (openMode === 'selectHide') {
      extra = {
        open: dropdownVisible,
      };
    }
    return extra;
  }, [openMode, dropdownVisible]);

  //获取数据
  const fetch = useCallback(
    async (keywords) => {
      requestTimeStamp = Date.now();
      const innerTimeStamp = requestTimeStamp;
      const newData = await getDataApi({
        filterInfo: {
          name: keywords,
          roleCodes,
          excludeIds,
        },
        pageInfo: {
          pageSize: 20,
        },
      });
      if (innerTimeStamp != requestTimeStamp) return;
      setData(newData);
      if (!newData?.length) {
        setVirtalData(false);
      }
    },
    [roleCodes, excludeIds],
  );

  // 弹窗onOK事件 提交数据格式统一
  const handlerChange = (submitData: any, selectedRows: any) => {
    if (!multiple && selectedRows.length == 0) {
      onChange && onChange('', selectedRows);
    } else {
      onChange && onChange(submitData, selectedRows);
    }
    setVisible(false);
    setSelectFocus(false);
  };

  // select 下拉框检索回调
  const handlerSelectorSearch = useCallback(
    _.debounce((keywords: any) => {
      if (_.isArray(users) && showDefaultData) return;
      const str = keywords.replace(symbolPattern, '');
      if (!showDefaultData && _.isArray(users)) {
        if (_.isEmpty(str)) {
          setData([]);
          return;
        }
        const data = users?.filter((user) => user?.userLoginName?.includes(str) || user?.userName.includes(str));
        setData(data);
        return;
      }
      fetch(str);
    }, 100),
    [users, showDefaultData],
  );

  //选择改变
  const handlerSelectorChange = (id: any, rows: any[]) => {
    const isLoginName = valueProp && valueProp === 'userLoginName';
    let newRows;
    if (isLoginName) {
      if (multiple) {
        const arr: any = [];
        id?.map((item: any) => {
          const record = isLoginName ? getUserInfo(undefined, item) : getUserInfo(item);
          arr.push(record);
        });
        newRows = _.uniqBy([...arr, ...rows], 'userLoginName').filter((item) => {
          return !isEmpty(item);
          //  && ['userLoginName', 'userName', 'id'].every(key=> !isEmpty(item[key]))
        });
      } else {
        newRows = [isLoginName ? getUserInfo(undefined, id) : getUserInfo(id)];
      }
    }
    onChange && onChange(id, newRows);
    setSelectFocus(false);
    openMode == 'selectHide' && setDropdownVisible(false);
  };

  // 基础选择的 数据来源
  const dataSource = useMemo(() => {
    let res: any = data;
    if (_.isArray(users) && showDefaultData) {
      res = users.map((item) => {
        return {
          ...item,
          combineLabel: setCustomLabel(item),
        };
      });
    } else if (_.isArray(users) && !showDefaultData) {
      return res.map((item: any) => {
        return {
          ...item,
          combineLabel: setCustomLabel(item),
        };
      });
    } else if (props.isActive) {
      res = data.filter((item: any) => item.isActive === props.isActive);
    }
    return res; // 返回展开渲染的数据
  }, [users, data, showDefaultData]);

  // 为 renderItem 提供的 option 的 jsx 布局
  const renderLabel = useCallback(
    (user, size = 'small') => {
      if (_.isEmpty(user)) {
        return null;
      }
      return (
        <>
          <Avatar icon="user" size={size} src={getAvatar(user)} style={{ marginRight: 5, top: -2 }} alt="avatar" />
          <span>{setCustomLabel(user)}</span>
        </>
      );
    },
    [setCustomLabel],
  );

  //下拉时
  const onDropdownVisibleChange = (open: boolean) => {
    setDropdownVisible(open);
    if (open && _.isEmpty(dataSource)) {
      fetch('');
    }
    if (!open) {
      setVirtalData(true);
    }
  };

  // select 选择项 自定义渲染，组件必传两个参数
  const renderItem = useCallback(
    (user: any, Option: any) => (
      <Option
        key={user[valueProp]}
        userName={user.userName}
        combineLabel={setCustomLabel(user)}
        value={user[valueProp]}
      >
        {renderLabel(user, sizeCount(size))}
      </Option>
    ),
    [valueProp, size, renderLabel],
  );

  // 用于接收外部传递的选项的label，一般应用于选择的项不再列表中
  const optionLabel = useMemo(() => {
    if (!value) return null;
    const isLoginName = valueProp && valueProp === 'userLoginName' ? true : false;
    if (Array.isArray(value)) return getUserLabels(value, !isLoginName);
    const record = isLoginName ? getUserInfo('', value) : getUserInfo(value);
    if (!record) return value;
    return record.userName;
  }, [value, valueProp, renderLabel, multiple]);

  useEffect(() => {
    if (_.isNull(users) || _.isUndefined(users)) {
      setVirtalData(true);
    } else if (!users?.length) {
      setNoData(true);
    }
  }, [users]);

  return (
    <GridCellEditWrapper autoFocus={autoFocus} onBlur={onBlur} visible={visible || selectFocus || dropdownVisible}>
      {props.edit === 'EDIT' ? (
        <BaseSelect
          // 数据
          getPopupContainer={getGantPopupContainer}
          value={value}
          labelProp={labelProp}
          optionLabel={optionLabel}
          renderItem={renderItem}
          dataSource={dataSource}
          // selectorId={`UserSelector:${userId}`} // 存储在 storage 的key，以登录用户作为唯一字段，切换账号后，使用不同的缓存
          valueProp={valueProp}
          // 参数
          multiple={multiple}
          size={size}
          showLoupe={showLoupe}
          isFilter={users ? true : false}
          // 方法
          onSearch={handlerSelectorSearch}
          onChange={handlerSelectorChange}
          onLoupeClick={() => setVisible(true)} // 控制进阶检索的方法
          // renderReadElement={renderReadElement} // selector 组件无此属性
          onFocus={() => setSelectFocus(true)}
          onBlur={() => setSelectFocus(false)}
          onDropdownVisibleChange={onDropdownVisibleChange}
          // 其他 属性，方法
          {...restProps}
          useStorage={false}
          useCache={false}
          {...extraProps}
          virtalData={virtalData}
          noData={noData}
        />
      ) : (
        <div style={{ height: '24.85px' }}>{optionLabel}</div>
      )}
      <SelectorModal
        // 数据
        users={users}
        valueProp={valueProp}
        defaultValue={value}
        // 参数
        visible={visible}
        multiple={multiple}
        isActive={props.hasOwnProperty('isActive') ? props.isActive : null} // 暂不支持，需要后端api数据调整，添加 isActice字段
        // 方法
        onOk={handlerChange}
        onCancel={() => setVisible(false)}
        isShowSkipButton={isShowSkipButton}
      />
    </GridCellEditWrapper>
  );
};

// 部分props默认值
SelectorFormItem.defaultProps = {
  multiple: false,
  valueProp: 'id',
  labelProp: 'combineLabel',
  valuePropType: 'string',
  optionLabelProp: 'userName',
};

SelectorFormItem.setDefaultProps = (defaultProps: SelectorFormItemProps) => {
  Object.assign(SelectorFormItem.defaultProps, defaultProps);
};

export default SelectorFormItem;
